﻿using Microsoft.IdentityModel.Tokens;
using Prism.Commands;
using Prism.Services.Dialogs;
using SmartPlant.Core;
using SmartPlant.Core.Mvvm;
using SmartPlant.Model;
using SmartPlant.Model.Biz;
using SmartPlant.Model.DbContext.Biz;
using SmartPlant.Model.UI;
using SmartPlant.Services.Interfaces;
using SmartPlant.WinCore;
using SmartPlant.WinCore.Helper;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Telerik.Windows.Diagrams.Core;
using ICommand = System.Windows.Input.ICommand;

namespace SmartPlant.Modules.Base.ViewModels
{
    public class UserGroupSetRightViewModel : DialogViewModelBase, IDialogAware
    {
        /// <summary>
        /// 某个用户组的所有单元下的权限（m x n）总数
        /// </summary>
       
        private List<UserRightData> _userRightDatas;
        private readonly IPlantGroupService _pauService;

        private int _rightInBatchMode = 1;

        private TreeNodeModel _selectUnit = null;

        private DelegateCommand<object> _okDialogCommand;
        private IOAuthService _authService;
        public UserGroupSetRightViewModel(IDialogService dialogService, IPlantGroupService plantGroupService, IOAuthService oAuthService) : base(dialogService)
        {
            Title = "编辑用户组";
            _authService = oAuthService;
            _pauService = plantGroupService;
            _nodes = new TreeNodeModelList();
            _userRightDatas = new List<UserRightData>();
            _groupRights = new ObservableCollection<UserRightData>();
            _nodes.SelectChanged += _nodes_SelectChanged;
            ButtonContent = "所有单元允许";
        }
        public override async void OnDialogOpened(IDialogParameters parameters)
        {
            base.OnDialogOpened(parameters);
            await LoadUnitData();

            UserGroupId = parameters.GetValue<string>("groupId");
            if (!UserGroupId.IsNullOrEmpty())
            {
                _userRightDatas = await _authService.GetGroup(UserGroupId);
            }
        }
        #region binding
        private string _userGroupId;
        public string UserGroupId
        {
            get { return _userGroupId; }
            set { SetProperty(ref _userGroupId, value); }
        }
        private string _buttonContent;
        public string ButtonContent
        {
            get { return _buttonContent; }
            set { SetProperty(ref _buttonContent, value); }
        }

        public ICommand OkDialogCommand
        {
            get
            {
                if (_okDialogCommand != null) return _okDialogCommand;
                _okDialogCommand = new DelegateCommand<object>(onOkDialogCommand);
                return _okDialogCommand;
            }
        }
        private ICommand _curUnitSetAllDialogCommand;
        /// <summary>
        /// 为当前单元批量设置
        /// </summary>
        /// <param name="obj"></param> 
        public ICommand curUnitSetAllDialogCommand
        {
            get
            {
                if (_curUnitSetAllDialogCommand != null)
                {
                    return _curUnitSetAllDialogCommand;
                }

                _curUnitSetAllDialogCommand = new DelegateCommand<object>(onCurUnitSetAllDialogCommand);
                return _curUnitSetAllDialogCommand;
            }
        }

        private ICommand _allUnitsSetAllDialogCommand;
        /// <summary>
        /// 为所有单元批量设置
        /// </summary>
        /// <param name="obj"></param> 
        public ICommand allUnitsSetAllDialogCommand
        {
            get
            {
                if (_allUnitsSetAllDialogCommand != null)
                {
                    return _allUnitsSetAllDialogCommand;
                }
                _allUnitsSetAllDialogCommand = new DelegateCommand<object>(onAllUnitsSetAllDialogCommand);
                return _allUnitsSetAllDialogCommand;
            }
        }



        private TreeNodeModelList _nodes;
        /// <summary>
        /// 绑定到xaml里的树
        /// </summary>
        public TreeNodeModelList TreeNodes
        {
            get
            {
                return _nodes;
            }
            set { SetProperty(ref _nodes, value); }
        }

        private ObservableCollection<UserRightData> _groupRights;

        /// <summary>
        /// 当前单元的所有right列表
        /// </summary>
        public ObservableCollection<UserRightData> RightItems
        {
            get
            {
                return _groupRights;
            }
            set { SetProperty(ref _groupRights, value); }
        }
        #endregion

        /// <summary>
        /// 作为委托绑定到selectChange的事件上。PBS目录树的复选框勾选后
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e">     </param>
        private void _nodes_SelectChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            var selectNode = _nodes.FindNodes(t => t.IsSelected == true && t.NodeType == TreeNodeType.Unit);
            if (_groupRights == null || _userRightDatas == null)
                return;

            RightItems.Clear();
            if (selectNode.IsEmpty()) return;

            _selectUnit = selectNode[0];

            var units = from c in _userRightDatas where c.PpauId == _selectUnit.Id select c;
            foreach (var unit in units)
            {
                RightItems.Add(unit);
            }
        }

        /// <summary>
        /// 调用API
        /// </summary>
        /// <param name="sender"></param>
        private async Task LoadUnitData()
        {
            //var plants = await _pauService.GetPlantGroupTreeAsync(GlobalObject.CurrentProject.ProjId.ToString());

            TreeNodes.Clear();
            //var trees = new TreeNodeModelList();
            TreeNodes.BeginUpdate();
            foreach (var plant in GlobalObject.Plants)
            {
                var plantNode = new TreeNodeRadiolModel(TreeNodes, null)
                {
                    NodeName = plant.PlantName,
                    Id = plant.PLANT_ID.ToString(),
                    IconGlyph = "&#xe13a;",
                    NodeType = TreeNodeType.Plant
                };
                if (plant.Area != null && plant.Area.Count > 0)
                {
                    foreach (var area in plant.Area)
                    {
                        var areaNode = new TreeNodeRadiolModel(TreeNodes, plantNode)
                        {
                            NodeName = area.AreaName,
                            Id = area.AreaId.ToString(),
                            IconGlyph = "&#xe13b;",
                            NodeType = TreeNodeType.Area
                        };
                        if (area.Unit != null && area.Unit.Count > 0)
                        {
                            foreach (var unit in area.Unit)
                            {
                                var unitNode = new TreeNodeRadiolModel(TreeNodes, areaNode)
                                {
                                    NodeName = unit.UnitName,
                                    IconGlyph = "&#xe13c;",
                                    Id = unit.UnitId.ToString(),
                                    NodeType = TreeNodeType.Unit,
                                    Unit = unit
                                };
                                areaNode.Nodes.Add(unitNode);
                            }
                        }
                        plantNode.Nodes.Add(areaNode);
                    }
                }
                TreeNodes.Add(plantNode);
            }
            TreeNodes.EndUpdate();
        }

        /// <summary>
        /// 保存权限设置
        /// </summary>
        /// <param name="parameter"></param>
        private async void onOkDialogCommand(object parameter)
        {
            if (_selectUnit.IsNullOrEmpty())
            {
                Dialog.ShowAltert("您尚未选择单元。");
                return;
            }
            if (RightItems.IsEmpty())
            {
                Dialog.ShowAltert("您尚未设置单元权限。");
                return;
            }
            try
            {
                bool? r = r = await _authService.SetGroup(RightItems.ToList(), UserGroupId, _selectUnit.Id);
                if (r.HasValue && r.Value)
                {
                    Dialog.ShowAltert("编辑用户组权限信息成功！！！");
                }
            }
            catch (Exception x)
            {
                var xMessage = $"编辑用户组权限信息失败：{x.Message}！！！";
                LoggerHelper.Current.Error(xMessage, x);
                Dialog.ShowAltert(xMessage);
            }
        }


        private void onCurUnitSetAllDialogCommand(object obj)
        {
            RightItems.ForEach(item =>
            {
                item.IsEnabled = _rightInBatchMode;
            });
            if (_rightInBatchMode == 1)
            {
                _rightInBatchMode = 0;
            }
            else if (_rightInBatchMode == 0)
            {
                _rightInBatchMode = 1;
            }
        }

        private async void onAllUnitsSetAllDialogCommand(object obj)
        {
            Dialog.ShowQuestion($"是否要设置成{ButtonContent}权限？",
           async P =>
            {
                switch (P.Result)
                {
                    case ButtonResult.OK:
                    case ButtonResult.Yes:
                        
                       
                        try
                        {
                            bool? r;
                            if (ButtonContent == "所有单元允许")
                            { 
                                r =  await _authService.SetGlobalGroup(1, UserGroupId);
                                _userRightDatas.ForEach(item =>
                                {
                                    item.IsEnabled = 1;
                                });
                            }
                            else
                            {
                                 r =  await _authService.SetGlobalGroup(0, UserGroupId);
                                _userRightDatas.ForEach(item =>
                                {
                                    item.IsEnabled = 0;
                                });
                            }
                            if (r.HasValue && r.Value)
                            {
                                Dialog.ShowAltert("编辑用户组权限信息成功！！！");
                            }
                        }
                        catch (Exception x)
                        {
                            var xMessage = $"编辑用户组权限信息失败：{x.Message}！！！";
                            LoggerHelper.Current.Error(xMessage, x);
                            Dialog.ShowAltert(xMessage);
                        }
                        if (ButtonContent == "所有单元允许")
                        {
                            ButtonContent = "所有单元拒绝";
                        }
                        else
                        {
                            ButtonContent = "所有单元允许";
                        }
                        break;
                    default:
                        break;
                }
            });





        }
    }
}
